import { reactive, ref } from 'vue'
import { useUserStore } from '@/stores/user'

export function usePhoneLogin() {
  const userStore = useUserStore()

  // 表单数据
  const form = reactive({
    phone: '',
    verifyCode: '',
  })

  // 状态管理
  const loading = ref(false)
  const sendingCode = ref(false)
  const countdown = ref(0)
  const privacyAccepted = ref(false)

  // Logo图片
  const logoImage = ref('/static/logo.png')

  // 手机号验证
  function validatePhone(phone: string): boolean {
    const phoneRegex = /^1[3-9]\d{9}$/
    return phoneRegex.test(phone)
  }

  // 验证码验证
  function validateVerifyCode(code: string): boolean {
    return /^\d{6}$/.test(code)
  }

  // 发送验证码
  async function sendVerifyCode() {
    if (!form.phone.trim()) {
      uni.showToast({
        title: '请输入手机号',
        icon: 'none',
      })
      return
    }

    if (!validatePhone(form.phone)) {
      uni.showToast({
        title: '请输入正确的手机号',
        icon: 'none',
      })
      return
    }

    sendingCode.value = true

    try {
      // 模拟发送验证码API
      await new Promise(resolve => setTimeout(resolve, 1000))

      uni.showToast({
        title: '验证码已发送',
        icon: 'success',
      })

      // 开始倒计时
      startCountdown()
    }
    catch (error: any) {
      uni.showToast({
        title: error?.message || '发送失败，请重试',
        icon: 'none',
      })
    }
    finally {
      sendingCode.value = false
    }
  }

  // 开始倒计时
  function startCountdown() {
    countdown.value = 60
    const timer = setInterval(() => {
      countdown.value--
      if (countdown.value <= 0) {
        clearInterval(timer)
      }
    }, 1000)
  }

  // 处理登录
  async function handleLogin() {
    if (!form.phone.trim()) {
      uni.showToast({
        title: '请输入手机号',
        icon: 'none',
      })
      return
    }

    if (!validatePhone(form.phone)) {
      uni.showToast({
        title: '请输入正确的手机号',
        icon: 'none',
      })
      return
    }

    if (!form.verifyCode.trim()) {
      uni.showToast({
        title: '请输入验证码',
        icon: 'none',
      })
      return
    }

    if (!validateVerifyCode(form.verifyCode)) {
      uni.showToast({
        title: '请输入6位数验证码',
        icon: 'none',
      })
      return
    }

    if (!privacyAccepted.value) {
      uni.showToast({
        title: '请同意隐私政策',
        icon: 'none',
      })
      return
    }

    loading.value = true

    try {
      // 模拟手机验证码登录API
      const success = await userStore.phoneLogin(form.phone, form.verifyCode)

      if (success) {
        uni.showToast({
          title: '登录成功',
          icon: 'success',
        })

        setTimeout(() => {
          const pages = getCurrentPages()
          const currentPage = pages[pages.length - 1] as any
          const redirect = currentPage?.options?.redirect || currentPage?.$page?.options?.redirect

          if (redirect) {
            uni.redirectTo({ url: decodeURIComponent(redirect) })
          }
          else {
            uni.switchTab({ url: '/pages/home/index' })
          }
        }, 1500)
      }
    }
    catch (error: any) {
      uni.showToast({
        title: error?.message || '登录失败',
        icon: 'none',
      })
      form.verifyCode = ''
    }
    finally {
      loading.value = false
    }
  }

  // 返回登录页
  function goBack() {
    uni.navigateBack()
  }

  // 跳转到密码登录
  function goToPasswordLogin() {
    uni.redirectTo({ url: '/pages/login/index' })
  }

  // 隐私政策
  function handlePrivacyPolicy() {
    uni.navigateTo({ url: '/pages/privacy/index' })
  }

  // 切换隐私政策同意状态
  function togglePrivacyAccepted() {
    privacyAccepted.value = !privacyAccepted.value
  }

  return {
    form,
    loading,
    sendingCode,
    countdown,
    privacyAccepted,
    logoImage,
    sendVerifyCode,
    handleLogin,
    goBack,
    goToPasswordLogin,
    handlePrivacyPolicy,
    togglePrivacyAccepted,
  }
}
